<template>
	<div id="bianji">
		<el-dialog title="提示" :visible.sync="showdown" width="50%" :before-close="handleClose">
		<el-row>
            <el-col :span="4" ref="rolename">角色名称</el-col>
            <el-col :span="20"> <el-input v-model="role.roleName"></el-input></el-col>
        </el-row>
        <el-row>
            <el-tree
                :data="allPermissions"
                show-checkbox
                node-key="permissionDesc"
                ref="tree"
                :props="defaultProps"
                >
            </el-tree>
        </el-row>

		<span slot="footer" class="dialog-footer">
	        <el-button @click="handleClose">取 消</el-button>
	        <el-button type="primary" @click="addnewone">确 定</el-button>
	    </span>
	</el-dialog>
	</div>
</template>

<script>
	export default{
		props: ["showdown","role"],
		data() {
			// 自定义的验证规则

			return {

				defaultProps: {
					children: 'children',
					label: 'label',
				},
				refs:{}
				

			}
		},

		computed: {
			allPermissions() {

				return this.$store.getters.allPermissions;
			},

		},

		methods: {
			handleClose() {
				this.$parent.showdown = false;
			},
			addnewone() {
				
				var permission = [];
				this.$refs.tree.getCheckedNodes().forEach((item) => {
					
					permission.push(item._id)
				})
				var params = {
	                permissions: permissions,
	                roleName: this.role.roleName,
	                id: this.role._id
	            }
				this.$http.post('/updateRoleInfo',params)
	            .then((res)=>{
	                this.$message({
	                    message: res.success?res.message+'成功':res.message+'失败',
	                    type: res.success?'success':'danger'
	                })
	            });

			}

		},
	    watch: {
	        role(newValue){
	            setTimeout(()=>{
	                //根据要编辑的角色中已有的权限,设置默认选中权限
	                var defaultPermission = [];
	                this.$store.state.allPermissions.forEach((item)=>{
	                    if(newValue.permissions.indexOf(item._id)!=-1){
	                        defaultPermission.push(item);
	                    }
	                })
	                this.$refs.tree.setCheckedNodes(defaultPermission)
	            },0)
	        }
	    }
	}
</script>

<style lang="scss" scoped>
</style>